package com.heer.gymnasium.module.speedy.views;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;

import com.google.gson.Gson;
import com.heer.amap.utils.ToastUtil;
import com.heer.gymnasium.R;
import com.heer.gymnasium.api.ResponseData.ApiResponse;
import com.heer.gymnasium.api.callback.BaseCallback;
import com.heer.gymnasium.base.BaseActivity;
import com.heer.gymnasium.constant.Type;
import com.heer.gymnasium.module.login.views.LoginActivity;
import com.heer.gymnasium.module.order.beans.OrderResponseBean;
import com.heer.gymnasium.module.order.views.OrderActivity;
import com.heer.gymnasium.module.reservation.beans.ReservationBookItemResponseBean;
import com.heer.gymnasium.module.reservation.beans.ReservationGridBean;
import com.heer.gymnasium.util.StringUtils;
import com.zhihuiyun.library.calendar.data.CalendarDate;
import com.zhihuiyun.library.calendar.fragment.CalendarViewFragment;
import com.zhihuiyun.library.calendar.fragment.CalendarViewPagerFragment;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Response;

import static com.heer.gymnasium.constant.Extras.EXTRA_ID;

/**
 * Created by yan
 * on 2018/3/7
 */

public class CalendarActivity extends BaseActivity implements
        CalendarViewPagerFragment.OnPageChangeListener,
        CalendarViewFragment.OnDateClickListener,
        CalendarViewFragment.OnDateCancelListener {
    private static final int RES_ID_LAYOUT = R.layout.layout_calendar;
    private static final int RES_ID_Fy = R.id.layout_calendar_fy;
    private static final int RES_ID_V = R.id.layout_calendar_v;
    private static final int RES_ID_TV = R.id.layout_calendar_tv;

    public static final int requestCode = 1;
    private Activity $this;
    private List<CalendarDate> calendarDateList;

    public static void startActivity(Activity activity, String id, List<ReservationGridBean> data) {
        Intent intent = new Intent(activity, CalendarActivity.class);
        intent.putExtra(EXTRA_ID, id);
        intent.putParcelableArrayListExtra(EXTRA_DATA, (ArrayList<? extends Parcelable>) data);
        activity.startActivity(intent);
    }


    @Override
    protected void init() {
        super.init();
        $this = this;
        setContentView(RES_ID_LAYOUT);
    }

    @Override
    protected void initView() {
        super.initView();
        calendarDateList = new ArrayList<>();
        initFragment();
    }

    @OnClick(RES_ID_V)
    public void onClickForBG() {
        finish();
    }

    @OnClick(RES_ID_TV)
    public void onClickForOrder() {
        List<ReservationGridBean> data = getIntent().getParcelableArrayListExtra(EXTRA_DATA);
        if (data != null && data.size() > 0) {
            addOrder(data);
        }
    }

    private void initFragment() {
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction tx = fm.beginTransaction();
        Fragment fragment = CalendarViewPagerFragment.newInstance(false);
        tx.replace(RES_ID_Fy, fragment);
        tx.commit();
    }

    @Override
    public void onPageChange(int year, int month) {

    }

    @Override
    public void onDateClick(CalendarDate calendarDate) {
        calendarDateList.add(calendarDate);
    }

    @Override
    public void onDateCancel(CalendarDate calendarDate) {
        calendarDateList.remove(calendarDate);
    }

    /**
     * 下单
     */
    private void addOrder(List<ReservationGridBean> data) {
        List<ReservationGridBean> newList = new ArrayList<>();
        String order_type = null,
                is_auto = null,
                place_id = null,
                start_time = null,
                end_time = null,
                plan_info = null,
                card_id = null,
                coach_id = null,
                num = null,
                order_id = null,
                corps_id = null,
                order_num = null,
                info = null,
                category_id = null;
        for (ReservationGridBean item : data) {
            if (TextUtils.equals(ReservationGridBean.STATUS_MINE, item.getState())) {
                for (int i = 0; i < calendarDateList.size(); i++) {
                    String startTime = StringUtils.getPhpDateFormat(StringUtils.toLong(item.getStartTime()), new SimpleDateFormat("HH:mm:ss"));
                    String endTime = StringUtils.getPhpDateFormat(StringUtils.toLong(item.getEndTime()), new SimpleDateFormat("HH:mm:ss"));
                    String year = calendarDateList.get(i).getSolar().solarYear + "";
                    String month = (calendarDateList.get(i).getSolar().solarMonth + "").length() == 1 ? ("0" + calendarDateList.get(i).getSolar().solarMonth) : calendarDateList.get(i).getSolar().solarMonth + "";
                    String day = (calendarDateList.get(i).getSolar().solarDay + "").length() == 1 ? ("0" + calendarDateList.get(i).getSolar().solarDay) : calendarDateList.get(i).getSolar().solarDay + "";
                    ReservationGridBean bean = new ReservationGridBean();
                    bean.setCategoryId(item.getCategoryId());
                    bean.setId(item.getId());
                    bean.setState(item.getState());
                    bean.setKey(item.getKey());
                    bean.setText(item.getText());

                    bean.setStartTime(StringUtils.dateStringToLong(year + "-" + month + "-" + day + " " + startTime) + "");
                    bean.setEndTime(StringUtils.dateStringToLong(year + "-" + month + "-" + day + " " + endTime) + "");
                    newList.add(bean);
                }
            }
        }

        if (newList.size() == 0) {
            ToastUtil.show($this, "请选择要预定的日期!");
            return;
        }

        if (newList.size() == 1) {
            order_type = Type.ORDER_ONE_STDIUM;
            place_id = newList.get(0).getId();
            start_time = newList.get(0).getStartTime();
            end_time = newList.get(0).getEndTime();
        } else {
            order_type = Type.ORDER_MORE_STDIUM;
            plan_info = new Gson().toJson(ReservationBookItemResponseBean.dataChange(newList));
        }

        final String finalOrder_type = order_type;
        mAppHelper.apiService().addOrder(order_type,
                place_id,
                start_time,
                end_time,
                plan_info,
                card_id,
                coach_id,
                num,
                corps_id,
                order_id,
                order_num,
                info, category_id, "").enqueue(new BaseCallback<ApiResponse<OrderResponseBean>>() {
            @Override
            public void onSuccess(Call<ApiResponse<OrderResponseBean>> call, Response<ApiResponse<OrderResponseBean>> response) {
                OrderActivity.startActivity($this, OrderActivity.OrderType.from_coupon, response.body().getData().getOrder_id(), finalOrder_type, true);
            }
        });
    }
}
